package com.todod.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import sun.net.www.protocol.http.HttpURLConnection;
import sun.net.www.protocol.https.HttpsURLConnectionImpl;

/**
 * 
 */
public final class HttpUtil {

	/**
	 * 禁止实例化
	 */
	private HttpUtil() {
	}

	/**
	 * Map<String, String> parameters = new HashMap<String, String>();
	 * parameters.put("echostr", echostr); HttpUtil.doGet("", parameters);
	 * 
	 * @param domain
	 * @param parameters
	 * @return
	 */
	public static String doGet(String domain, Map<String, String> parameters) {
		return doGet(domain, parameters, "UTF-8");
	}

	/**
	 * Map<String, String> parameters = new HashMap<String, String>();
	 * parameters.put("echostr", echostr); HttpUtil.doGet("", parameters);
	 * 
	 * @param domain
	 * @param parameters
	 * @return
	 */
	public static String doGet(String domain, Map<String, String> parameters, String code) {

		String getURL = domain + "?";
		StringBuffer sb = new StringBuffer();
		try {
			if (parameters != null) {
				for (String key : parameters.keySet()) {
					String value = parameters.get(key);
					if (StringUtils.isNotBlank(value)) {
						getURL += key + "=" + URLEncoder.encode(parameters.get(key), code) + "&";
					} else {
						getURL += key + "=" + "&";
					}

				}
			}
			URL url = new URL(getURL.substring(0, getURL.length() - 1));
			if (getURL.indexOf("https") == 0) {
				HttpsURLConnectionImpl connection = (HttpsURLConnectionImpl) url.openConnection();
				connection.connect();
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String lines;
				while ((lines = reader.readLine()) != null) {
					sb.append(lines);
				}
				reader.close();
				connection.disconnect();
			} else {
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.connect();
				BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String lines;
				while ((lines = reader.readLine()) != null) {
					sb.append(lines);
				}
				reader.close();
				connection.disconnect();
			}
			return sb.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("finally")
	public static String doPost(String path, String params) {
		String getURL = path;
		StringBuffer sb = new StringBuffer();
		PrintWriter out = null;
		BufferedReader reader = null;
		try {

			URL url = new URL(getURL);
			if (getURL.indexOf("https") == 0) {
				HttpsURLConnectionImpl connection = (HttpsURLConnectionImpl) url.openConnection();
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Accept-Charset", "utf-8");
				connection.setRequestProperty("contentType", "utf-8");
				connection.setDoOutput(true);
				out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
				out.println(params);
				out.flush();
				reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String lines;
				while ((lines = reader.readLine()) != null) {
					sb.append(lines);
				}
				reader.close();

			} else {
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Accept-Charset", "utf-8");
				connection.setRequestProperty("contentType", "application/x-www-form-urlencoded");
				connection.setDoOutput(true);
				out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
				out.println(params);
				out.flush();
				reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
				String lines;
				while ((lines = reader.readLine()) != null) {
					sb.append(lines);
				}
				reader.close();
				connection.disconnect();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		} finally {
			out.close();
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return sb.toString();

		}

	}

	/**
	 * 向目的URL发送get请求
	 * 
	 * @param url    目的url
	 * @param params 发送的参数
	 * @return
	 */
	public static String sendGetRequest(String url, MultiValueMap<String, String> params) {
		RestTemplate client = new RestTemplate();
		HttpHeaders headers = new HttpHeaders();
		HttpMethod method = HttpMethod.GET;
		// 以表单的方式提交
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		// 将请求头部和参数合成一个请求
		HttpEntity<MultiValueMap<String, String>> requestEntity = null;
		if (params == null) {
			requestEntity = new HttpEntity<>(headers);
		} else {
			requestEntity = new HttpEntity<>(params, headers);
		}

		// 执行HTTP请求，将返回的结构使用ResultVO类格式化
		ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);

		return response.getBody();
	}
}